<?php
namespace Home\Controller;
use Think\Controller;
class AdminController extends  HomeController {
	//商家后台首页

   public function index()
    {
        
        $item=D('Item');
        $arg['page']=I('get.page',1,'strip_tags');
        $arg['platid']=1; //默认显示平台产品
        $result=$item->index($arg);
        $this->assign('items',$result['item']);
        
        $this->assign('pagearr',$result['pagearr']);
        /*顶级类目**/
        $toptype=M('type')->where("pid=0")->getField("typeid,typename");
       $this->assign('toptype',$toptype);

        $this->display('index');
    }
	//查看商品
	public function getItem(){
		$itemid=I('get.itemid','','strip_tags');
      if(!$itemid) return false;
      //获取分类树
     // $type=new \Admin\Controller\TypeController();
     // $type=A('Daili://Admin/TypeController');
	  $typearr=$this->getListCat();
      //获取商品基本信息
      $item=M('item');
      $iteminfo=$item->where('itemid=%d',$itemid)->select();
      //获取该类目下的所有属性
		$typeproperty=M('type a')->join('inner join '. C('DB_PREFIX').'type_property b on a.typeid=b.typeid ')
		          ->where('a.typeid=%d',$iteminfo[0]['typeid'])
		          ->getField('b.propertyid,a.typeid,a.typename,b.propertyname');
		  if(!empty($typeproperty))
		  {
		  	foreach($typeproperty as $key=>&$value)
		  	{
		 	$where['propertyid']=$key;
		 	$value['select']=M('type_property a')->join('inner join '.C('DB_PREFIX').'type_propertyvalue b on a.propertyid=b.propertyid')
		 		             ->where('a.propertyid=%d',$where['propertyid'])
		 		             ->getField('b.valueid,a.propertyid,a.propertyname,b.propertyvalue ');
		 	}

		  }  
		//获取已选择的属性
		$seledpro=M('item_property')->where('itemid=%d',$iteminfo[0]['itemid'])->getField('propertyid,propertyvalueid');
		 foreach($typeproperty as $key=>&$value)
		 {
             
		 	foreach($value['select'] as $k=>&$v)
		 	{
		 		
		 		if($v['valueid']==$seledpro[$key])
		 		{

		 			$v['selected']='true';
		 		}
		 	}
		 }
		//获取该类目下所有品牌
		 $brands=M('type_brand a ')->join('inner join '.C('DB_PREFIX').'brand b on a.brandid= b.brandid')
		         ->where('b.isdel=0 AND a.typeid='.$iteminfo[0]['typeid'])
		         ->getField('b.brandid,b.brandname');
		 
		 //获取该类目下所有规格
		 $spec_type=M('type_spec a ')->join('inner join '.C('DB_PREFIX').'spec b  on a.specid =b.specid ')
		  			->where('a.typeid=%d',$iteminfo[0]['typeid'])->getField('a.specid,a.typeid,b.`name`');
		 if(!empty($spec_type))
		 {
		 	foreach($spec_type as $key=>&$value)
		 	{
		 			$where['specid']=$key;
		 			$value['specval']=M('specval')->where('specid=%d',$where['specid'])->getField('specvalid,specid,name');
		 	}
		 }
		 //该产品选中的规格
		 $serspec=M('item_spec')->where('itemid=%d',$itemid)->getField('specid,self');
		 foreach($serspec as $k=>&$v){
		 	$v=unserialize($v);
		 }
		 foreach($spec_type as $key=>&$value){
		 	foreach($value['specval'] as $k=>&$v){
		 		foreach($serspec[$key] as $i=>$sname)
		 		 {
		 		 	if($i==$v['specvalid']){
		 		 		$v['checked']='true';
		 		 	}
		 		}
		 		
		 	}
		 }
		//判断此商品是否为货品(即不同规格对应不同价格和库存)
	  $products=M('product')->where('itemid=%d',$itemid)->getField('productid,itemid,inventory,price');
	  if($products){
         $productspecs=M('product_spec')->where('itemid=%d',$itemid)->select(); 
         foreach($productspecs  as $spec){
         		$products[$spec["productid"]]["specs"][$spec["specid"]] =$spec["specvalid"];
         }  
	  }
	  //获取商品详情
	  $detail=M('item_desc')->where('itemid=%d',$itemid)->getField('itemdesc');
	  $this->assign('detail',$detail);
	  $this->assign('typearr',$typearr);
	  $this->assign('products',$products);
 	  $this->assign('iteminfo',$iteminfo[0]);
	  $this->assign('brands',$brands);
	  $this->assign('typeproperty',$typeproperty);
	  $this->assign('specs',$spec_type);
	  
      $this->display('getitem');
	}

	/**
	 *
	 * 返回已经确定子分类的类别属性，计算等级
	 *
	 */
	public function getListCat($data = array(),$level = 0) {
		$cats = array();
		!$data && $data = $this->getCats();
		if(!$data) return $cats;
		foreach($data as $key => $val) {
			$cats[$val['typeid']] = &$data[$key];
			$cats[$val['typeid']]['level'] = $level;
			if( isset( $val['children'] ) ) {
				$cats[$val['typeid']]['haschild'] = 1;
				$cats += $this->getListCat($val['children'],$level + 1);
				unset($data[$key]['children']);
			} 
		}
		return $cats;
	}
	
	/**
	 *
	 * 获取所有类别
	 *
	 */
	protected function getCats($return = 'tree') {
		static $retarr;
		if(isset($retarr[$return])) return $retarr[$return];

		$cats = M('type')->getField('typeid,typename,pid');
		if($return == 'tree')
		{			//返回数组
			$tree = array();

			foreach($cats as $cat)
			 {	//循环cat
				if(isset($cats[$cat['pid']])) 
				{//非第一级
					$cats[$cat['pid']]['children'][] = &$cats[$cat['typeid']];
				} else
				 {//第一级
					$tree[] = &$cats[$cat['typeid']];

				}
			}
			$retarr[$return] = $tree;
		} else if($return == 'source')
		 {//返回source
			$retarr[$return] = $cats;
		}
		return $retarr[$return];
	}




	 public function Type2Brand(){
        $typeid=!empty($_COOKIE['typeid'])?$_COOKIE['typeid']:0;
        $brandid=!empty($_COOKIE['brandid'])?$_COOKIE['brandid']:0;

        //获取所有类目
        $type=new \Home\Controller\TypeController();
        $typearr=$type->getListCat();
        //获取所有品牌
        $brands=M('brand')->order('brandid desc')->getField('brandid,brandname');
        $string="";
        foreach ($typearr as $key => $value)
        {
            if($typeid ==$key)
            {
                $string.='<option value='.$key.' selected >'.str_repeat('&nbsp;&nbsp;&nbsp;',$value['level']).$value['typename'].'</option>';
            }else
            {
                $string.='<option value='.$key.' >'.str_repeat('&nbsp;&nbsp;&nbsp;',$value['level']).$value['typename'].'</option>';
            }
        }
        

        $bsting='';
        foreach ($brands as $key => $value)
         {
            if ($key==$brandid)
            {
                $bsting.='<option value='.$key.' selected >'.$value.'</option>';
            }else
            {
                $bsting.='<option value='.$key.' >'.$value.'</option>';
            }
        }
        $result['string']=$string;
        $result['bsting']=$bsting;
        echo json_encode($result,JSON_UNESCAPED_UNICODE);

    }
    /*
     *类目、品牌 通过ajax 联动
     */
    public function getBrand()
    {
        $typeid=I('get.typeid',0,'strip_tags');
        $brandid=!empty($_COOKIE['brandid'])?$_COOKIE['brandid']:0;
        //获取所有品牌
        $brands=M('brand a')->join('inner join '.C(DB_PREFIX).'type_brand b on a.brandid=b.brandid')
                ->where('b.typeid=%d',$typeid)->order('a.brandid desc')->getField('a.brandid,a.brandname');
        $bsting="<option value=0>选择品牌</option>";
        foreach ($brands as $key => $value)
         {
            if ($key==$brandid)
            {
                $bsting.='<option value='.$key.' selected >'.$value.'</option>';
            }else
            {
                $bsting.='<option value='.$key.' >'.$value.'</option>';
            }
        }
        echo json_encode($bsting,JSON_UNESCAPED_UNICODE);
    }


    /*
     * ajax 筛选商品
     * @param 
     * echo json
     */
    public function ajaxItem(){
        $arg=array();
        $arg['typeid']=I('post.typeid',0,'strip_tags');
        $arg['brandid']=I('post.brandid',0,'strip_tags');
        $arg['keywords']=I('post.keywords','','strip_tags');
        $arg['platid']=I('post.platid','','strip_tags');
        $arg['page']=I('post.page',1,'strip_tags');

        $item=D('item');
        $result=$item->index($arg);

  

        if(!empty($result['item'])){
            $result['status']=1;
            $result['item']=array_values($result['item']);
            echo json_encode($result,JSON_UNESCAPED_UNICODE);
            return '';

        }

        $result['status']=0;
        $result['message']='暂无数据';
        echo  json_encode($result,JSON_UNESCAPED_UNICODE);
    }


    /**
      * 获取二级类目
      */
     public function stype(){
        $where['pid']=$_GET['typeid'];
       $setype=M('type')->where($where)->getField('typeid,typename');
       $str='';
   foreach($setype as  $k=>$v){
    $str.= '<option value='.$k.'>'.$v.'</option>';

   }
  echo $str;
       


     }
     /**
      * 获取品牌
      */
     public function brand(){
    $where['a.typeid']=$_GET['brandid'];
    $brands=M('type_brand a')
    ->join('cart_brand b on a.brandid=b.brandid')
    ->where($where)
    ->getField('b.brandid,b.brandname');
   foreach ($brands as $k=>$v){
    $str.= '<option value='.$k.'>'.$v.'</option>';
   }
   echo $str;
     }




      /*
     *商品预览
     *@param Itemid 
     *
     */
    public function viewItem()
    {
        $itemid=I('get.itemid',0,'strip_tags');
        $result=M('item_desc')->where('itemid=%d',$itemid)->getField('itemdesc');
        $this->assign('itemdesc',$result);
        $this->display('preview');
    }

      /*
     *ajax 弹出货品规格（颜色，价格，库存，供应价）
     *@param itemid
     *@return json
     */
      public function ajaxProduct()
      {
        $itemid=I('post.itemid',0,'strip_tags');
        $item=M('item a');
        $products=$item->join('inner join '.C('DB_PREFIX').'product b on a.itemid=b.itemid')
        ->where('a.itemid=%d',$itemid)
        ->getField('b.productid,a.itemid,a.itemname,a.bn,b.price,b.color,b.supprice,b.inventory');
        $result=array();
        $result['status']=!empty($products)?1:0;
        $result['message']=empty($products)?'此产品没有规格':'';
        $result['products']=!empty($products)?array_values($products):'';

        echo json_encode($result);
    }




	
}